// import store from '../store';
import Request from '@/js_sdk/luch-request/luch-request';
import Store from '@/store'

const http = new Request();
http.setConfig((config) => {
  config.baseURL = 'https://cnodejs.org/api/v1';
  config.timeout = 1000 * 30;
  return config;
});

http.interceptors.request.use(
  (config, cancel) => {
    if (config.method === 'GET') {
      config.params = { ...config.params, accesstoken: Store.state?.user?.token || undefined }
    } else {
      config.data = { ...config.data, accesstoken: Store.state?.user?.token || undefined }
    }
    /* cancel 为函数，如果调用会取消本次请求。需要注意：调用cancel,本次请求的catch仍会执行。必须return config */
    // if (store.getters.token) {
    //   config.header.token = store.getters.token;
    // }
    Store.dispatch('loading/loadingNum_add_action')
    if (Store.state?.loading?.loadingNum > 0) {
      uni.showLoading({
        mask: true,
        title: "加载中",
      });
    }
    return config;
  },
  (config) => {
    return Promise.reject(config);
  }
);

http.interceptors.response.use(
  (response) => {
    Store.dispatch('loading/loadingNum_reduce_action')
    if (Store.state?.loading?.loadingNum <= 0) {
      uni.hideLoading();
    }
    return response.data;
  },
  (error) => {
    /*  对响应错误做点什么 （statusCode !== 200）*/
    Store.dispatch('loading/loadingNum_Reset_action')
    uni.showToast({
      icon: "error",
      title: error.data.error_msg || '系统错误,请稍后再试',
      duration: 2000,
    });
    return Promise.reject(error.data);
  }
);
export default http;
